using UnityEngine;
using WebSocketSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
using System;
using PimDeWitte.UnityMainThreadDispatcher;

public class GameController : MonoBehaviour
{
    private float rotationSpeed = 5.0f;
    private Color newColor = Color.red;

    public Transform cubeTransform;
    public GameObject[] enemyPrefabs;  // Array to store multiple enemy prefabs
    public GameObject targetCube;      // Target cube for enemy generation
    public float spawnRadius = 5.0f;    // Random spawn radius for enemies

    private WebSocket webSocket;

    private void Start()
    {
        webSocket = new WebSocket("ws://192.168.43.1:8083/websocket");
        webSocket.OnMessage += OnWebSocketMessage;
        webSocket.Connect();
        Debug.Log("WebSocket connected to ws://192.168.43.1:8083/websocket");

        // Check references
        if (enemyPrefabs != null && enemyPrefabs.Length > 0 && cubeTransform != null)
        {
            // Do additional initialization if needed
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
        }
        //GenerateRandomEnemy(username);
    }

    void Update()
    {
        cubeTransform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
        //GenerateRandomEnemy(username);

    }

    private void OnWebSocketMessage(object sender, MessageEventArgs e)
    {
        string message = e.Data;
        string utf8Message = Encoding.UTF8.GetString(Encoding.Default.GetBytes(message));

        try
        {
            JObject jsonData = JObject.Parse(utf8Message);
            int messageType = Convert.ToInt32(jsonData["Type"]);

            switch (messageType)
            {
                case 1:
                    HandleNormalBarrage(jsonData);
                    break;

                case 3:
                    HandleUserJoin(jsonData);
                    break;

                case 5:
                    HandleMoveAndSkill(jsonData);
                    break;

                default:
                    Debug.Log("Unhandled message type: " + messageType);
                    break;
            }
        }
        catch (JsonReaderException ex)
        {
            Debug.LogError("Error parsing JSON: " + ex.Message);
        }

        if (!webSocket.IsAlive)
        {
            Debug.LogWarning("WebSocket connection closed, reconnecting...");
            webSocket.Connect();
            Debug.Log("WebSocket reco ws://192.168.43.1:8083/websocket");
        }
    }

    private void HandleNormalBarrage(JObject jsonData)
    {
        // Handle normal barrage logic here
    }

    private void HandleUserJoin(JObject jsonData)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() =>
        { 
        Debug.Log("HandleUserJoin started");
        string userData = jsonData["Data"].ToString();
        JObject userObject = JObject.Parse(userData);

        string username = userObject["User"]["Nickname"].ToString();
        int followerCount = Convert.ToInt32(userObject["User"]["FollowerCount"]);
        Debug.Log("User joined: " + username + " with " + followerCount + " followers");

        GenerateRandomEnemy(username);
        Debug.Log("HandleUserJoin completed");
        });
    }

    private void HandleMoveAndSkill(JObject jsonData)
    {
        // Handle move and skill logic here
    }

    private void OnDestroy()
    {
        if (webSocket != null && webSocket.IsAlive)
        {
            webSocket.Close();
        }
    }

    private void GenerateRandomEnemy(string username)
    {
        if (targetCube != null && enemyPrefabs != null && enemyPrefabs.Length > 0)
        {
            Vector3 cubePosition = targetCube.transform.position;
            Vector2 randomOffset = UnityEngine.Random.insideUnitCircle * spawnRadius;  // 修改这里
            cubePosition += new Vector3(randomOffset.x, 0.0f, randomOffset.y);

            GameObject selectedPrefab = enemyPrefabs[UnityEngine.Random.Range(0, enemyPrefabs.Length)];  // 修改这里
            GameObject enemy = Instantiate(selectedPrefab, cubePosition, Quaternion.identity);
            Rigidbody enemyRigidbody = enemy.AddComponent<Rigidbody>();
            enemyRigidbody.freezeRotation = true;

            Debug.Log("Enemy generated at: " + cubePosition + ", Username: " + username);
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
        }
    }
}